1.code
import React, { useState, useEffect } from 'react';
import styles from './ImageBounce.module.css';
import Image from 'next/image';
function ImageBounce() {
const [positionX, setPositionX] = useState(0); //水平初始位置
const [positionY, setPositionY] = useState(0); //垂直初始位置
const [velocityX, setVelocityX] = useState(2); //水平初始速度
const [velocityY, setVelocityY] = useState(2); //垂直初始速度
const containerWidth = 300; //容器寬度
const containerHeight = 300; //容器高度
useEffect(() => {
const updatePosition = () => {
const newPosX = positionX + velocityX;
const newPosY = positionY + velocityY;
//邊界檢測,碰到時會隨機反彈
if (newPosX < 0 || newPosX + 150 > containerWidth) {
setVelocityX(-Math.random() * 2 + 1); //隨機水平速度
}
if (newPosY < 0 || newPosY + 150 > containerHeight) {
setVelocityY(-Math.random() * 2 + 1); //隨機垂直速度
}
setPositionX(newPosX);
setPositionY(newPosY);
};
const animationFrame = requestAnimationFrame(() => {
updatePosition();
});
return () => {
cancelAnimationFrame(animationFrame);
};
}, [positionX, positionY, velocityX, velocityY]);
return (
<div className={styles.container}>
<div
className={`${styles.image} ${styles['bouncing-image']}`}
style={{ left: `${positionX}px`, top: `${positionY}px` }}
>
<Image src="/S__2990088_0.jpg" width={150} height={150} alt="Bouncing Image" />
</div>
</div>
);
}
export default ImageBounce;
.container {
position: relative;
width: 300px;
height: 300px;
overflow: hidden;
border: 1px solid #ccc;
}
.image {
position: absolute;
transition: left 0.1s, top 0.1s;
}
.bouncing-image {
max-width: 100%;
height: auto;
display: block;
}
2.實作